/**
 * Alipay.com Inc.
 * Copyright (c) 2004-2014 All Rights Reserved.
 */
package com.alipay.servlet.gateway;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.constants.AlipayServiceEnvConstants;
import com.alipay.dispatcher.Dispatcher;
import com.alipay.executor.ActionExecutor;
import com.alipay.f2fpay.ToAlipayQrTradePay;
import com.alipay.factory.AlipayAPIClientFactory;
import com.alipay.util.LogUtil;
import com.alipay.util.RequestUtil;

/**
 * 开发者网关，支付宝所有主动和开发者的交互会经过此网关进入开发者系统
 * 
 * @author taixu.zqq
 * @version $Id: GatewayServlet.java, v 0.1 2014年7月22日 下午5:59:55 taixu.zqq Exp $
 */
public class QrCodeServlet extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 1210436705188940602L;

    /** 
     * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
                                                                          IOException {
        this.doPost(req, resp);
    }

    /**
     * 网关处理
     * 
     * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
                                                                                   throws ServletException,                                                                                  IOException {
        //支付宝响应消息  
        JSONObject json=new JSONObject();
        json.put("success", false);

        //1. 解析请求参数
        Map<String, String> params = RequestUtil.getRequestParams(request);

        //打印本次请求日志，开发者自行决定是否需要
        LogUtil.log("Order paramas", params.toString());
    	String out_trade_no=params.get("out_trade_no"); //商户唯一订单号
		String total_amount=params.get("total_amount");
		String goods_detail=params.get("goods_detail");
		String operator_id=params.get("operator_id");
		String subject = params.get("subject");
        try {
        	AlipayTradePrecreateResponse rs=qrPay(out_trade_no, total_amount, subject,goods_detail,operator_id);
        	if (null != response && rs.isSuccess()) {
				if (rs.getCode().equals("10000")) {
					System.out.println("商户订单号："+rs.getOutTradeNo());
					System.out.println("二维码值："+rs.getQrCode());//商户将此二维码值生成二维码，然后展示给用户，用户用支付宝手机钱包扫码完成支付
					json.put("success", true);
					json.put("qrcode", rs.getQrCode());
					//二维码的生成，网上有许多开源方法，可以参看：http://blog.csdn.net/feiyu84/article/details/9089497
					
				} else {

				//打印错误码
				System.out.println("错误码："+rs.getSubCode());
				System.out.println("错误描述："+rs.getSubMsg());
				}
			}
        } catch (Exception exception) {
           

        } finally {
            //5. 响应结果加签及返回
            try {
               
                //http 内容应答
                response.reset();
                response.setContentType("text/xml;charset=UTF-8");
                PrintWriter printWriter = response.getWriter();
                printWriter.print(json.toString());
                response.flushBuffer();

                //开发者自行决定是否要记录，视自己需求
                LogUtil.log("responseMsg", json.toString());

            } catch (Exception alipayApiException) {
                //开发者可以根据异常自行进行处理
                alipayApiException.printStackTrace();
            }
        }
    }

    public static AlipayTradePrecreateResponse qrPay(String out_trade_no,String total_amount,String subject,String goods_detail,String operator_id) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time_expire= sdf.format(System.currentTimeMillis()+1*60*60*1000);
		
		StringBuilder sb = new StringBuilder();
		sb.append("{\"out_trade_no\":\"" + out_trade_no + "\",");
		sb.append("\"total_amount\":\""+total_amount+"\",\"discountable_amount\":\"0.00\",");
		sb.append("\"subject\":\""+subject+"\",\"body\":\"test\",");
		//sb.append("\"goods_detail\":[{\"goods_id\":\"apple-01\",\"goods_name\":\"ipad\",\"goods_category\":\"7788230\",\"price\":\"88.00\",\"quantity\":\"1\"},{\"goods_id\":\"apple-02\",\"goods_name\":\"iphone\",\"goods_category\":\"7788231\",\"price\":\"88.00\",\"quantity\":\"1\"}],");
		sb.append("\"operator_id\":\""+operator_id+"\",\"store_id\":\"pudong001\",\"terminal_id\":\"t_001\",");
		sb.append("\"time_expire\":\""+time_expire+"\"}");
		System.out.println(sb.toString());

		AlipayClient alipayClient = AlipayAPIClientFactory.getAlipayClient();

		// 使用SDK，构建群发请求模型
		AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
		request.setBizContent(sb.toString());
		request.setNotifyUrl("http://sscloud.net:8080/fuwuchuang_demo/notify_url.jsp");
//		request.putOtherTextParam("ws_service_url", "http://unitradeprod.t15032aqcn.alipay.net:8080");
		AlipayTradePrecreateResponse response = null;
		try {

			// 使用SDK，调用交易下单接口
			response = alipayClient
					.execute(request);

			System.out.println(response.getBody());
			System.out.println(response.isSuccess());
			System.out.println(response.getMsg());
			// 这里只是简单的打印，请开发者根据实际情况自行进行处理
			if (null != response && response.isSuccess()) {
				if (response.getCode().equals("10000")) {
					System.out.println("商户订单号："+response.getOutTradeNo());
					System.out.println("二维码值："+response.getQrCode());//商户将此二维码值生成二维码，然后展示给用户，用户用支付宝手机钱包扫码完成支付
					//二维码的生成，网上有许多开源方法，可以参看：http://blog.csdn.net/feiyu84/article/details/9089497
					
				} else {

				//打印错误码
				System.out.println("错误码："+response.getSubCode());
				System.out.println("错误描述："+response.getSubMsg());
				}
			}
		} catch (AlipayApiException e) {
		}
		
		return response;
	}
	 

}
